/* eslint-disable global-require,no-console */
const path = require('node:path');
const fse = require('fs-extra');
const packageJson = require('../package.json');

const packageJsonPath = path.join(__dirname, '../package.json');

async function switchVersion() {
    let vue = null;

    try {
        vue = require('vue');
    } catch (error) {
        console.log(`[${packageJson.name}] cannot find Vue`);
    }

    const { version } = vue;

    if (typeof version !== 'string' || !(version.startsWith('2.') || version.startsWith('3.'))) {
        console.log(`[${packageJson.name}] need install Vue2/3`);

        return;
    }

    const isVue2 = version.startsWith('2.');
    const distDir = isVue2 ? 'dist/v2' : 'dist/v3';
    const exportJson = {
        main: `${distDir}/index.umd.js`,
        module: `${distDir}/index.es.js`,
        types: `${distDir}/index.d.ts`,
        style: `${distDir}/style.css`,
        exports: {
            '.': {
                types: `./${distDir}/index.d.ts`,
                import: `./${distDir}/index.es.js`,
                require: `./${distDir}/index.cjs.js`,
            },
            './style': `./${distDir}/style.css`,
        },
    };
    const newPackageJson = Object.assign(packageJson, exportJson);

    fse.writeJsonSync(packageJsonPath, newPackageJson, { spaces: '\t' });

    console.log(`[${packageJson.name}] Switch packageJson fields for Vue${version}`);
}

async function main() {
    await switchVersion();
}

main().catch((error) => {
    console.log(error);
});
